package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return com.sky.vo.OrderSubmitVO
     * @author zhupp
     * @create 2025/2/25
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        // 判断购物车中是否有商品
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectAllByUserId(userId);
        if (shoppingCartList == null) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 判断是该订单否有地址信息

        AddressBook addressBook = addressBookMapper.selectAddressById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 往订单表中插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+
                addressBook.getDistrictName()+addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(LocalDateTime.now().toString() + userId);
        orderMapper.insert(orders);

        // 往订单明细表中插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();

        for (ShoppingCart shoppingCartItem : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCartItem, orderDetail);
            orders.setConsignee(addressBook.getConsignee());
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        // 清空购物车
        shoppingCartMapper.deleteAll();
        // 封装OrderSubmitVO，返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return com.sky.vo.OrderPaymentVO
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        // 重新封装一个JSONObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 为替代微信支付成功后的数据库订单状态更新
        Integer orderPaidStatus = Orders.PAID; // 支付状态，已支付
        Integer orderStatus = Orders.TO_BE_CONFIRMED;  // 订单状态，待接单

        // 更新支付时间
        LocalDateTime check_out_time = LocalDateTime.now();

        // 获取订单号码
        String orderNumber = ordersPaymentDTO.getOrderNumber();

        Orders order = orderMapper.getByNumber(orderNumber);

        //给前端通知来单了，type,orderId content
        log.info("来单了");

        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",order.getId());
        map.put("content","订单号："+orderNumber);

        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        log.info("调佣updateStatus,用于替换微信支付更新数据库支付状态");
        orderMapper.updateStatus(orderStatus,orderPaidStatus,check_out_time,orderNumber);
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     *
     * @param page
     * @param pageSize
     * @param status
     * @return com.sky.result.PageResult
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public PageResult pageQuery4User(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> pageOrders = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();

        // 循环将明细数据添加到订单中
        pageOrders.forEach(p -> {
            List<OrderDetail> od = orderDetailMapper.getByOrderId(p.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(p, orderVO);
            orderVO.setOrderDetailList(od);
            orderVOList.add(orderVO);
        });

        return new PageResult(pageOrders.getTotal(), orderVOList);
    }

    /**
     * 查看订单详情
     * @param id
     * @return com.sky.vo.OrderVO
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public OrderVO getOrder(Long id) {
        Orders order = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单
     * @param orderId
     * @return void
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public void cancelOrder(Long orderId) {
        Orders order = new Orders();
        order.setId(orderId);
        order.setStatus(Orders.CANCELLED);
        orderMapper.update(order);
    }

    /**
     * 再来一单
     * @param orderId
     * @return void
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public void repetitionOrder(Long orderId) {
        // 获取上一个订单的内容
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
        // 添加到当前购物车中
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        orderDetailList.forEach(odl -> {
            BeanUtils.copyProperties(odl, shoppingCart);
            shoppingCartMapper.insert(shoppingCart);
        });

    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return java.util.List<com.sky.vo.OrderVO>
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }
    /**
     * 根据订单id获取菜品信息字符串
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     * @return com.sky.vo.OrderStatisticsVO
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public OrderStatisticsVO getOrderStatistics() {
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        statisticsVO.setConfirmed(orderMapper.selectCountByConf());
        statisticsVO.setDeliveryInProgress(orderMapper.selectCountByDelivery());
        statisticsVO.setToBeConfirmed(orderMapper.selectCountByToBeConf());
        return statisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     * @return void
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(orders);
    }

    /**
     *
     * @param ordersRejectionDTO
     * @return void
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 获取订单状态
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());
        Integer payStatus = ordersDB.getPayStatus();

        // 退款，只有已支付的订单才可以退款
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    orders.getNumber(),
//                    orders.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
            log.info("申请退款：{}");
        }
        // 拒单理由
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     * @return void
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public void cancelOrderAdmin(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     * @return void
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public void deliveryOrder(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param orderId
     * @return void
     * @author zhupp
     * @create 2025/2/26
     **/
    @Override
    public void completeOrder(Long orderId) {
        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 客户催单
     * @param id
     * @return void
     * @author zhupp
     * @create 2025/2/27
     **/
    @Override
    public void orderReminder(Long id) {
        Orders orders = orderMapper.getById(id);
        Map map = new HashMap();
        map.put("orderId", id);
        map.put("type", 2);
        map.put("content","订单号："+ orders.getNumber());

        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
